from datetime import datetime

import redis

from app.config.config import config
from app.settings import env
from common.database import db_connect
from model.user import User

db_session, Base, engine = db_connect()

def redis_connect():
    redis_config = config[env]
    pool = redis.ConnectionPool(
        host=redis_config.REDIS_HOST,
        port=redis_config.REDIS_PORT,
        db=redis_config.REDIS_DB,
        decode_responses=redis_config.REDIS_DECODE_RESPONSES
    )
    return redis.Redis(connection_pool=pool)


def model_list(result):
    user_list = []
    for row in result:
        dict_ = {}
        for k, v in row.__dict__.items():
            if k.startswith('_sa'):
                continue
            if isinstance(v, datetime):
                v = v.strftime('%Y-%m-%d %H:%M:%S')
            dict_[k] = v
        user_list.append(dict_)
    return user_list


def mysql_to_redis_string():
    redis_client = redis_connect()
    result = db_session.query(User).all()
    user_list = model_list(result)
    for user in user_list:
        redis_client.set('user:' + user['username'], str(user))


# mysql_to_redis_string()

def mysql_to_redis_hash():
    redis_client = redis_connect()
    result = db_session.query(User).all()
    user_list = model_list(result)
    for user in user_list:
        redis_client.hset('hash_user:' + user['username'], user['username'], user['password'])


mysql_to_redis_hash()
